package com.puppet.building182.controller;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.puppet.building182.pojo.House;
import com.puppet.building182.pojo.Result;
import com.puppet.building182.pojo.User;
import com.puppet.building182.pojo.VO.UseVO;
import com.puppet.building182.pojo.VO.UserVo;
import com.puppet.building182.pojo.enums.BuildingCode;
import com.puppet.building182.service.UserService;
import com.puppet.building182.utils.MinioUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    MinioUtils minioUtils;
    @Value("${spring.minio.url}")
    private String url;
    @Value("${spring.minio.bucket-name}")
    private String bucketName;

    @GetMapping("/{pageNum}/{pageSize}")
    public Result<?> getUser(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserVo> list = userService.getUser();
        PageInfo<UserVo> pageInfo = new PageInfo<>(list);
        return Result.ok(pageInfo);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result<?> deleteById(@PathVariable("id") Integer id) {
        return Result.ok(userService.deleteById(id), BuildingCode.DELETE_SUCCESS.getMessage());
    }

    @GetMapping("/getUserById/{id}")
    public Result<?> getUserById(@PathVariable("id")  Integer id) {
        return Result.ok(userService.getUserById(id));
    }

    @PutMapping
    public Result<?> updateUser(@RequestBody User user) {
        return Result.ok(userService.updateUser(user));
    }

    @PutMapping("/updateAllUser")
    public Result<?> updateAllUser(@RequestBody User users) {
        return Result.ok(userService.updateAllUser(users));
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody UseVO users, HttpSession session, HttpServletResponse response) throws UnsupportedEncodingException {
        User user = userService.login(users);
        session.setAttribute("user", user);
        if (users.isRememberMe()) {
            String jsonUser = JSON.toJSONString(user);
            String encodeUser = URLEncoder.encode(jsonUser, "utf-8");
            Cookie cookie = new Cookie("user", encodeUser);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);


        }
        return Result.ok(user, BuildingCode.LOGIN_SUCCESS.getMessage());
    }

    @GetMapping("/request")
    public Result<?> request(HttpSession session) {
        Object user = session.getAttribute("user");
        return Result.ok(user);
    }
    @DeleteMapping("/deleteMsg")
    public Result<?> deleteMsg(HttpSession session,HttpServletResponse response) {
        Object user = session.getAttribute("user");
        if (user != null) {
            // 移除特定的Session属性
            session.removeAttribute("user");
            // 或者完全使Session失效（根据需要选择）
            // session.invalidate();
            Cookie cookie = new Cookie("user", null);
            cookie.setPath("/");
            cookie.setMaxAge(0); // 立即过期
            response.addCookie(cookie);
            return Result.ok("用户数据已从Session中删除");
        } else {
            return Result.fail("Session中没有用户数据");
        }
    }

    @PostMapping("/uploadImg")
    public Result<?> uploadImg(@RequestParam("file") MultipartFile file) {
        String newFileName = UUID.randomUUID().toString();//随机生成编码
        newFileName = newFileName.substring(0, 8);//生成的图片编码长度
        minioUtils.upload(file, newFileName);
        System.out.println("上传成功");
        String fileUrl = url + "/" + bucketName + "/" + newFileName;
        System.out.println(fileUrl);
        return Result.ok(fileUrl);

    }
}
